<template>
	<view class="container">
		<camera id="myCamera" class="camera" device-position="front" flash="off" frame-size="small" @error="error"></camera>
		<view class="overlay">
			<!-- Header with timer -->
			<view class="header">
				<text class="timer">{{ recordingTime }}</text>
			</view>
			<!-- Question and progress bar -->
			<view class="bottom-section">
				<view class="question-container">
					<view class="progress">
						<text>{{ currentQuestionIndex }}/共{{ totalQuestions }}题</text>
						<view class="progress-bar">
							<view class="progress-bar-inner" :style="{ width: progressWidth + '%' }"></view>
						</view>
					</view>
					<view class="question">
						<text>{{ currentQuestion }}</text>
					</view>
				</view>
				<!-- Next button -->
				<view class="button-container">
					<button type="primary" class="custom-button" @click="nextQuestion">{{ buttonText }}</button>
				</view>
				<view class="disclaimer">
					<text>本小程序结果为多模态模型生成，请用户以专业医生诊断结果为准</text>
				</view>
			</view>
			<!-- 上传和检测提示 -->
			<view v-if="isUploading" class="uploading-message">
				<text>上传进行中，请稍候...</text>
			</view>
			<view v-if="isWaitingForResult" class="waiting-message">
				<text>检测进行中，请您稍后在历史记录中查看...</text>
			</view>
			<view v-if="iserror" class="waiting-message">
				<text>模型错误，请您重新测试!</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				recordingTime: '00:00',
				displaytimer: null,
				recordingtimer: null,
				startTime: 0,
				starttime1: 0, //记录时间戳
				currentQuestionIndex: 1,
				totalQuestions: 16,
				ctx: null, // 保存相机上下文
				questions: [
					"请你尽可能全面准确的回答 今天过得怎么样",
					"家乡是哪里的",
					"最喜欢你家乡的哪些美食 景点",
					"家人同事同学朋友 关系处得怎么样",
					"性格内向还是外向一些",
					"最近两周心情怎么样",
					"目前的学习或工作的兴趣如何",
					"容不容易责备自己 感到自己连累了其他人",
					"觉得自己的行动思考或说话都比较迟钝",
					"是否经常感到紧张焦虑担心惶恐不安",
					"有没有哪段时间 感到兴奋或亢奋或者精力旺盛",
					"有没有哪段时间 连续几天持续地感到烦躁易怒,以至于争论吵架或打架或者对着外人大吼",
					"有没有哪段时间 你总喜欢滔滔不绝地讲话，说话快得让人难以理解",
					"有没有哪段时间 你觉得自己思维比以往格外活跃脑子格外聪明",
					"有没有哪段时间 你认为有人在暗中监视你 故意议论你或企图伤害你吗",
					"有没有哪段时间 你能听到其他人不能听到的声音或者看到别人看不到的东西 有的话 请你仔细讲一下",
				],
				videoSegments: [], // 存储视频片段的路径
				chunkSize: [], // 分片大小 5MB
				currentChunk: 0, // 当前上传的分片
				totalChunks: 0, // 总分片数
				isRecording: false,
				recordingDuration: 0, // 当前片段录制的时长
				isPaused: false, // 上传是否暂停
				uploadFileSize: 0, // 文件大小
				fileMD5: '', // 文件的 MD5
				isUploading: false, // 是否正在上传
				isWaitingForResult: false, // 是否等待结果
				isfinish: 0,
				timestamp: [0], //返回给后端的时间戳
				iserror: false,
				isclick: false,
				filename: '',
				pauseTime: 0, // 记录暂停时间
				timechunk: [],
			};
		},
		computed: {
			currentQuestion() {
				return this.questions[this.currentQuestionIndex - 1];
			},
			progressWidth() {
				return (this.currentQuestionIndex / this.totalQuestions) * 100;
			},
			buttonText() {
				return this.currentQuestionIndex === this.totalQuestions ? '完成录像' : '下一题';
			}
		},
		methods: {
			startRecordingTimer() {
				this.startRecording();
				this.startTime = Date.now();
				this.displaytimer = setInterval(() => {
					const elapsed = Date.now() - this.startTime;
					const minutes = Math.floor(elapsed / 60000);
					const seconds = Math.floor((elapsed % 60000) / 1000);
					this.recordingTime = `${this.padZero(minutes)}:${this.padZero(seconds)}`;
				}, 1000);
				console.log("timer:", this.displaytimer);
			},
			startRecording() {
				if (!this.ctx) {
					console.error('Camera context is not initialized.');
					return;
				}
				this.isRecording = true;
				this.recordSegment();
			},
			recordSegment() {
				this.ctx.startRecord({
					success: () => {
						console.log('Recording started');
						this.pauseTime = Date.now();
						this.isPaused=true;
						this.recordingDuration = 0;
						if (this.starttime1 === 0) {
							this.starttime1 = Date.now();
						}
						// 控制录制时长的计时器
						this.recordingTimer = setInterval(() => {
							this.recordingDuration += 1;
							if (this.recordingDuration >= 29) {
								this.stopRecordingSegment(0); // 接近 30 秒时停止录制
							}
						}, 1000);
					},
					fail: (err) => {
						console.error('Start recording failed:', err);
					}
				});
			},
			stopRecordingSegment(isend) {
				console.log('Stopping current segment...');
				if (!this.ctx) {
					console.error('Camera context not found');
					return;
				}

				// 清除录制时长的计时器
				if (this.recordingTimer) {
					clearInterval(this.recordingTimer);
					this.recordingTimer = null;
				}
				this.timechunk.push(Date.now() - this.pauseTime);
				this.isPaused=false;
				console.log(this.timechunk);
				this.ctx.stopRecord({
					success: (res) => {
						console.log('Recording stopped, video path:', res.tempVideoPath);

						// 将临时文件保存为持久文件
						wx.saveFile({
							tempFilePath: res.tempVideoPath,
							success: (saveResult) => {
								const savedFilePath = saveResult.savedFilePath;
								console.log('文件已保存到本地持久路径:', savedFilePath);

								this.totalChunks += 1;

								if (this.totalChunks === 1) {
									this.filename = savedFilePath.split('/').pop();
									wx.getFileInfo({
										filePath: savedFilePath,
										digestAlgorithm: 'md5',
										success: (fileInfo) => {
											this.fileMD5 = fileInfo.digest;
											console.log('文件MD5:', this.fileMD5);
										},
										fail: (err) => {
											console.error('获取文件信息失败: ', err);
										}
									});
								}

								wx.getFileInfo({
									filePath: savedFilePath,
									success: (fileInfo) => {
										this.uploadFileSize += fileInfo.size;
										this.chunkSize.push(fileInfo.size);
										console.log('文件大小:', this.uploadFileSize);

										// 上传持久文件路径而不是临时路径
										this.uploadNextChunk(isend, savedFilePath,
											fileInfo.size);
									},
									fail: (err) => {
										console.error('获取文件信息失败: ', err);
									}
								});
							},
							fail: (err) => {
								console.error('保存文件失败:', err);
							}
						});
						if (this.isRecording) {
							this.recordSegment(); // 继续录制下一个片段
						}
					},
					fail: (err) => {
						console.error('Stop recording failed:', err);
					}
				});
			},
			stopRecordingCompletely() {
				this.isRecording = false;
				// setTimeout(() => {
					this.stopRecordingSegment(1); // 停止当前片段
					this.isUploading = true;
					console.log('All segments recorded:', this.videoSegments);
				// }, 2000); // 延迟 2 秒
			},
				prepareUpload() {
						if (!this.uploadFileSize || !this.fileMD5) {
							console.log('文件大小：', this.uploadFileSize);
							console.log('文件MD5：', this.fileMD5);
							console.error('上传文件大小或 MD5 未初始化');
							return;
						}

						// 开始分片上传
						this.currentChunk = 0;
						this.uploadNextChunk(); // 开始上传
					},
					uploadNextChunk(isend, path, size) {
						console.log("index", this.currentChunk);
						console.log("md5", this.fileMD5);
						this.currentChunk++;
						wx.uploadFile({
							url: this.$globalData.upload_url, // 替换为你的后端接口
							filePath: path,
							name: 'chunk',
							formData: {
								md5: this.fileMD5,
								index: this.currentChunk,
								isend: isend, // 将布尔值转换为字符串
								fileSize: this.uploadFileSize,
								fileName: this.filename,
								chunkSize: size,
								userInfo: JSON.stringify({
									userId: this.$globalData.userID,
									username: this.$globalData.username
								}),
								timetamps: JSON.stringify(Array.from(this.timestamp)),
								isupload: 0,
							},
							success: (res) => {
								console.log(res.data);
								this.isfinish += 1;
								const responseData = JSON.parse(res.data);
								if (responseData.code === 201) {
									console.log(`分片 ${this.currentChunk} 上传成功`);
									wx.removeSavedFile({
										filePath: path,
										success: () => {
											console.log('上传完成，已删除本地文件:', path);
										},
										fail: (err) => {
											console.error('删除本地文件失败:', err);
										}
									});
								}
								if (this.currentChunk < this.totalChunks) {
									console.log("没干啥事");
								} else {
									if (responseData.code === 200) {
										console.log('所有分片上传完成，等待最终结果');
										this.isUploading = false;
										setTimeout(() => {
											this.processFinalResult();
										}, 2000); // 2000 毫秒延时，即 2 秒
									} else if (responseData.code === -1) {
										console.log('模型错误');
										this.iserror = true;
									}
								}
							},
							fail: (err) => {
								console.error('上传失败: ', err);
								this.isUploading = false;
								wx.showToast({
									title: '上传失败，请您重新测试',
									icon: 'none',
								});
								setTimeout(() => {
									this.processFinalResult();
								}, 2000); // 2000 毫秒延时，即 2 秒
							},
						});
					},
					calculateTimechunkSum() {
						// 检查数组是否为空
						if (!this.timechunk || this.timechunk.length === 0) {
							return 0; // 如果数组为空，则返回 0
						}

						// 使用 reduce 计算总和
						return this.timechunk.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
					},
					nextQuestion() {
						if (this.currentQuestionIndex < this.totalQuestions) {
							console.log(this.timechunk);
							if(this.isPaused){
								this.timestamp.push((Date.now() - this.pauseTime + this.calculateTimechunkSum()) / 1000);
							}else{
								this.timestamp.push((Date.now() - this.pauseTime) / 1000);
							}
							this.currentQuestionIndex += 1;
						} else {
							if (!this.isclick) {
								console.log("你不许再暂停了！");
								clearInterval(this.displaytimer);
								if(this.isPaused){
									this.timestamp.push((Date.now() - this.pauseTime + this.calculateTimechunkSum()) / 1000);
								}else{
									this.timestamp.push((Date.now() - this.pauseTime) / 1000);
								}
								console.log(this.timestamp);
								this.stopRecordingCompletely();
								this.isclick = true;
							}
						}
					},
					padZero(num) {
						return num < 10 ? `0${num}` : num;
					},
					error(e) {
						console.log(e.detail);
					},
					showWaitingMessage() {
						this.isWaitingForResult = true; // 显示检测提示
					},
					processFinalResult() {
						this.isWaitingForResult = false; // 关闭检测中提示
						this.navigateToResult(); // 跳转至结果页面，传递结果

					},
					// 跳转到结果页面并传递检测分数
					navigateToResult() {
						uni.navigateTo({
							url: `/pages/homepage/homepage`, // 假设结果页面路径为 /pages/result/result
						});
					},
					stopAllRecording() {
						if (this.isRecording) {
							this.isRecording = false;
							if (this.recordingTimer) {
								clearInterval(this.recordingTimer);
								this.recordingTimer = null;
							}
							if (this.displaytimer) {
								clearInterval(this.displaytimer);
								this.displaytimer = null;
							}
							// 停止相机录制
							this.ctx.stopRecord({
								success: () => {
									console.log('Recording stopped successfully.');
								},
								fail: (err) => {
									console.error('Failed to stop recording:', err);
								},
							});
						}
					}
			},
			mounted() {
				this.ctx = uni.createCameraContext(); // 初始化相机上下文
				setTimeout(() => {
					this.startRecordingTimer();
				}, 500); // 延迟500ms以确保相机组件加载完成
			},
			onUnload() {
				// 微信小程序特有的生命周期方法，可以保证在页面卸载时清理资源
				this.stopAllRecording();
			},
			beforeDestroy() {
				this.stopAllRecording(); // 离开页面时清理所有录制
			}
		};
</script>

<style scoped>
	.container {
		position: relative;
		width: 100%;
		height: 100vh;
		overflow: hidden;
	}

	.camera {
		position: absolute;
		width: 100%;
		height: 100%;
		z-index: 1;
	}

	.overlay {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		z-index: 2;
		background: rgba(0, 0, 0, 0.3);
	}

	.header {
		text-align: center;
		padding: 20rpx 0;
		font-size: 36rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.timer {
		background-color: red;
		color: white;
		padding: 10rpx;
		border-radius: 10rpx;
	}

	.bottom-section {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 100%;
		position: absolute;
		bottom: 20rpx;
		padding-bottom: 20rpx;
	}

	.question-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 90%;
		padding: 20rpx;
		background-color: rgba(255, 255, 255, 0.1);
		box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.2);
		border-radius: 10rpx;
		margin-bottom: 20rpx;
	}

	.progress {
		width: 100%;
		margin-bottom: 20rpx;
		text-align: center;
	}

	.progress-bar {
		width: 100%;
		height: 10rpx;
		background-color: #ccc;
		border-radius: 5rpx;
		overflow: hidden;
	}

	.progress-bar-inner {
		height: 100%;
		background-color: #87CEEB;
	}

	.question {
		width: 100%;
		text-align: center;
		margin-bottom: 20rpx;
	}

	.button-container {
		display: flex;
		justify-content: center;
		width: 100%;
		margin-bottom: 20rpx;
	}

	.custom-button {
		width: 90%;
		background-color: #02b6c4 !important;
		border-radius: 40rpx !important;
		color: white !important;
		padding: 15rpx 0 !important;
		border: none !important;
		text-align: center !important;
	}

	.uploading-message {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		background-color: rgba(0, 0, 0, 0.7);
		color: white;
		padding: 20rpx;
		border-radius: 10rpx;
		font-size: 30rpx;
	}

	.waiting-message {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		background-color: rgba(0, 0, 0, 0.7);
		color: white;
		padding: 20rpx;
		border-radius: 10rpx;
		font-size: 30rpx;
	}
	.disclaimer {
	    text-align: center; /* 字体居中 */
	    color: white; /* 与提示词颜色一致 */
		width: 90%;
		padding-left: 0rpx;
		padding-top: 20rpx;
		padding-bottom: 20rpx;
		background: rgba(255, 255, 255, 0.1);
		box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.2);
		border-radius: 10rpx;
		margin-bottom: 20rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	  }
</style>